<template>
	<view class="container">
		<!-- 可滚动内容 - 添加下拉刷新功能 -->
		<scroll-view class="scroll-view" scroll-y @scroll="handleScroll" :scroll-top="scrollTop"
			:refresher-enabled="true" :refresher-triggered="refresherTriggered" @refresherrefresh="onRefresh"
			@refresherrestore="onRestore" refresher-background="#f5f5f5">
			<!-- 用户信息 -->
			<UserHeader :panel-data="panelData" :panel-other-data="panelOtherData" @avatar-upload="handleAvatarUpload"
				@edit-profile="handleEditProfile" @other-click="handleOtherClick" @image-error="handleImageError" />

			<!-- 内容区域 -->
			<ContentSection :tabs="tabs" :active-tab="activeTab" :posts="posts" :item-width="itemWidth"
				@tab-change="switchTab" @post-click="handlePostClick" />
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed } from 'vue'
	import UserHeader from './components/UserHeader.vue'
	import ContentSection from './components/ContentSection.vue'
	import { getPostForUser } from '@/api/post/post'
	import type { PostBasicInfo } from '@/api/post/post'
	import { getPanelDataForUser, type PanelData } from '@/api/follow/follow'
	import useUserStore from '@/store/modules/user'

	interface PanelDataItem {
		value : number | string
		label : string
	}

	interface PanelOtherDataItem {
		title : string
		label : string
	}

	interface ScrollEvent {
		detail : {
			scrollTop : number
		}
	}

	const userStore = useUserStore()

	// 改为
	const userId = computed(() => userStore.user.userId)

	// 响应式数据
	const panelData = ref<PanelDataItem[]>([
		{
			value: 0,
			label: '关注'
		},
		{
			value: 0,
			label: '粉丝'
		},
		{
			value: 0,
			label: '获赞与收藏'
		}
	])

	const panelOtherData = ref<PanelOtherDataItem[]>([
		{
			title: '我的圈子',
			label: '创建属于你的圈子'
		},
		{
			title: '购物',
			label: '好逛好玩又好买'
		},
		{
			title: '订单',
			label: '查看我的订单'
		},
		{
			title: '收货地址',
			label: '管理我的收货地址'
		},
		{
			title: '答题记录',
			label: '查看我的答题记录'
		},
		{
			title: '测试注册',
			label: '10个商品'
		}
		// {
		// 	title: '测试标签',
		// 	label: '10个商品'
		// }
	])

	const navBarBackground = ref<string>('red')
	const titleOpacity = ref<number>(0)
	const scrollTop = ref<number>(0)
	const activeTab = ref<number>(0)
	const tabs = ref<string[]>(['笔记', '收藏', '赞过'])
	const posts = ref<PostBasicInfo[]>()
	const itemWidth = ref<number>(0)

	// 响应式数据
	// 在现有的响应式数据后添加
	const refresherTriggered = ref<boolean>(false)

	const calculateLayout = () : void => {
		const { windowWidth } = uni.getWindowInfo()
		itemWidth.value = (windowWidth - 32) / 2
	}

	const handleScroll = (e : ScrollEvent) : void => {
		const scrollTopValue = e.detail.scrollTop
		titleOpacity.value = Math.min(scrollTopValue / 100, 1)
		navBarBackground.value = `rgba(255,255,255,${Math.min(scrollTopValue / 80, 0.98)})`
	}

	const switchTab = (index : number) : void => {
		activeTab.value = index
		// 这里可以根据不同的tab加载不同的数据
		loadPostsByTab(index)
	}

	const loading = ref<boolean>(false);

	const loadPanelData = async (userId : number) => {
		try {
			const res = await getPanelDataForUser(userId)
			if (res.code === 200 && res.data && res.data.length > 0) {
				const data = res.data[0] // API返回的是数组，取第一个元素

				// 更新panelData
				panelData.value = [
					{
						value: data.followCount || 0,
						label: '关注'
					},
					{
						value: data.fansCount || 0,
						label: '粉丝'
					},
					{
						value: data.postLikeCount || 0,
						label: '获赞'
					}
				]
			}
		} catch (error) {
			console.error('加载面板数据失败:', error)
		}
	}

	// 加载tab数据
	const loadPostsByTab = async (tabIndex : number) : Promise<void> => {
		loading.value = true;
		try {
			const type = tabIndex + 1; // 0->1, 1->2, 2->3
			const query = {
				pageNum: 1,
				pageSize: 20
			};

			const result = await getPostForUser(type, userId.value, query);

			if (result.code === 200) {
				posts.value = result.rows || [];
			} else {
				uni.showToast({
					title: result.msg || '加载失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}

	const handlePostClick = (post : PostBasicInfo) : void => {
		// 跳转到帖子详情页
		uni.navigateTo({
			url: `/pages/post/postDetail?id=${post.id}`
		})
	}

	// UserHeader组件事件处理方法
	const handleAvatarUpload = () : void => {
		console.log('头像上传')
		uni.navigateTo({
			url: '/pages_mine/pages/avatar/index'
		});
	}

	const handleEditProfile = () : void => {
		console.log('编辑资料')
		uni.navigateTo({
			url: '/pages/mine/editUserInfo'
		})
	}

	const handleOtherClick = (item : PanelOtherDataItem) : void => {
		console.log('点击其他项目:', item)
		switch (item.title) {
			case '我的圈子':
				uni.navigateTo({ url: '/pages/circle/myCircle' })
				break
			case '购物':
				uni.navigateTo({ url: '/pages/mallMenu/index1' })
				break
			case '订单':
				uni.navigateTo({ url: '/pages/order/index' })
				break
			case '收货地址':
				uni.navigateTo({ url: '/pages/address/index' })
				break
			case '答题记录':
				uni.navigateTo({ url: '/pages/questionRecord/record' })
				break
			case '测试注册':
				uni.navigateTo({ url: '/pages/register/wxRegister' })
				break
			case '测试标签':
				uni.navigateTo({ url: '/pages/register/newUserSelect' })
				break
			default:
				break
		}
	}

	const handleImageError = () : void => {
		console.log('图片加载失败')
	}

	// 生命周期
	onMounted(() => {
		calculateLayout()
		loadPostsByTab(0) // 初始加载第一个tab的数据
		loadPanelData(userId.value)
	})

	// 下拉刷新处理方法
	const onRefresh = async () : Promise<void> => {
		refresherTriggered.value = true
		try {
			// 刷新用户信息
			await userStore.getInfo()

			// 重新加载当前tab的数据
			await loadPostsByTab(activeTab.value)

			// 刷新面板数据
			await loadPanelData(userId.value)

			uni.showToast({
				title: '刷新成功',
				icon: 'success',
				duration: 1500
			})
		} catch (error) {
			console.error('刷新失败:', error)
			uni.showToast({
				title: '刷新失败',
				icon: 'none',
				duration: 1500
			})
		} finally {
			// 延迟一点时间再结束刷新状态，让用户看到刷新效果
			setTimeout(() => {
				refresherTriggered.value = false
			}, 500)
		}
	}

	// 刷新恢复处理方法
	const onRestore = () : void => {
		refresherTriggered.value = false
	}
</script>

<style lang="scss" scoped>
	// 只保留容器相关的样式
	.container {
		height: 100vh;
	}

	.scroll-view {
		height: 100%;
	}
</style>